package com.icesoft.wechat.utils.http;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
@ServletComponentScan("com.icesoft")
public class RestTemplateConfiguration {

	public static RestTemplate DEFAULT_REST_TEMPLATE;

	static {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(2000);// 连接超时默认2s
		factory.setReadTimeout(30000);// 读取超时默认30s
		DEFAULT_REST_TEMPLATE = new RestTemplate(factory);
		List<HttpMessageConverter<?>> converterList = DEFAULT_REST_TEMPLATE.getMessageConverters();

		// 重新设置StringHttpMessageConverter字符集为UTF-8，解决中文乱码问题
		HttpMessageConverter<?> converterTarget = null;
		for (HttpMessageConverter<?> item : converterList) {
			if (StringHttpMessageConverter.class == item.getClass()) {
				converterTarget = item;
				break;
			}
		}
		if (null != converterTarget) {
			converterList.remove(converterTarget);
		}
		converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
		converterList.add(new WeChatMappingJackson2HttpMessageConverter());
	}

	// 初始化RestTemplate,并加入spring的Bean工厂，由spring统一管理
	@Bean
	@ConditionalOnMissingBean(RestTemplate.class)
	public RestTemplate getRestTemplate() {
		return DEFAULT_REST_TEMPLATE;
	}

}
